﻿using Ezpay.ServiceContract;
using Microsoft.Practices.Prism;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.Interactivity.InteractionRequest;
using Microsoft.Practices.Prism.Regions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace Ezpay.UI.ViewModels
{
    class NewCustomerViewModel : BaseViewModel
    {
        public ICommand AddServiceCommand { get; private set; }
        private IRegionManager _regionManager;
        private IEzpayService _ezpayService;
        public InteractionRequest<Notification> AddServiceRequest { get; set; }

        public CreateNewCustomerRequest Customer { get; private set; }

        public ICommand SaveCommand { get; private set; }
        
        public NewCustomerViewModel(IRegionManager regionManager, IEzpayService ezPayService)
        {
            _regionManager = regionManager;
            _ezpayService = ezPayService;

            Subscriptions = new ObservableCollection<Subscription>();
            AddServiceCommand = new DelegateCommand(AddService);
            AddServiceRequest = new InteractionRequest<Notification>();

            Customer = new CreateNewCustomerRequest();
            SaveCommand = new RelayCommand(Save);
        }

        private async void Save()
        {
            IsSaving = true;

            var response = await Task.Factory.StartNew(() =>
            {
                return _ezpayService.CreateNewCustomer(Customer);
            });

            IsSaving = false;

            var query = new UriQuery();
            query.Add("ID", response.CustomerID);

            _regionManager.ShowInMain("CustomerViewModel" + query.ToString());
        }

        private bool _isSaving;
        public bool IsSaving
        {
            get { return _isSaving; }
            set
            {
                _isSaving = value;
                RaisePropertyChanged(() => IsSaving);
            }
        }

        private void AddService()
        {
            var message = new Notification();
            message.Title = "Add new service";
            message.Content = new AddServiceViewModel();
            AddServiceRequest.Raise(message, OnServiceAdded);
        }

        private void OnServiceAdded(Notification message)
        {
            var vm = message.Content as AddServiceViewModel;
            if(vm.Result == true)
            {
                Subscriptions.Add(new Subscription()
                {
                    Type = vm.SelectedServiceType,
                    Description = vm.Description
                });
            }
        }

        public ObservableCollection<Subscription> Subscriptions { get; set; }
    }
}
